import React, { useRef, useMemo, useEffect } from 'react';
import { Dispatcher } from '@sui/sui';
import { addModel, createContextStateModel } from '@@/core/plugin-model';

const models = {};
addModel(models, 'context', createContextStateModel() );


export const dispatcher = new Dispatcher();

function Executor(props) {
  const { hook, onUpdate, namespace } = props;

  const updateRef = useRef(onUpdate);
  const initialLoad = useRef(false);

  let data;
  try {
    data = hook();
  } catch (e) {
    console.error(
      `plugin-model: Invoking '${namespace || 'unknown'}' model failed:`,
      e,
    );
  }

  // 首次执行时立刻返回初始值
  useMemo(() => {
    updateRef.current(data);
  }, []);

  // React 16.13 后 update 函数用 useEffect 包裹
  useEffect(() => {
    if (initialLoad.current) {
      updateRef.current(data);
    } else {
      initialLoad.current = true;
    }
  });

  return null;
}

export function ModelsProvider(props){
        return <>{Object.keys(models).map(namespace =>{
            return (<Executor
                        key={namespace}
                        namespace={namespace}
                        hook={models[namespace]}
                        onUpdate={
                           val => {
                                dispatcher.data[namespace] = val;
                                dispatcher.update(namespace);
                            }
                        }
                    />)
        })}
        { props.children }
        </>
}

export default models;